#include "HomographyWriter.h"

#include <deque>

/* file output */
#include <fstream>

/* strings and buffers */
#include <string>
#include <sstream>

#include <cv.h>
#include <highgui.h>

#include "../utils/Output.h"

#include "../Features.h"


HomographyWriter::HomographyWriter()
{
}

HomographyWriter::~HomographyWriter()
{
}


void HomographyWriter::writeToFile(std::deque<CvMat *> homographies, std::deque<Features::IDPair> idPairs, std::deque<std::string> imageLines){
	
	
	using std::string;
	using std::ofstream;
	using std::ostringstream;
	using std::ios_base; //that's a whole namespace
	using std::endl;
	
	
	//ofstream dataFile("PTO/input.pto", ios_base::trunc|ios_base::out);
	ofstream dataFile("homographies.txt", ios_base::trunc|ios_base::out);

	if(!dataFile.is_open()){
		Output::message("Could not open data file for output!", Output::CRITICAL);
	} else {
		
		
		
		dataFile << "# Homographies from images" << endl;
		dataFile << endl;
		
		
		dataFile << "# images" << endl;
		
		for (unsigned int i = 0; i < imageLines.size(); ++i) {
//			dataFile << "i ";
//			dataFile << "w" << imageSizes[i].width << " ";
//			dataFile << "h" << imageSizes[i].height << " ";
//			dataFile << imageParameters; //No endl!
//			dataFile << "\"" << imageLines[i] << "\"" << endl; ///TODO check for relative vs. absolute paths!
			dataFile << imageLines[i] << endl;
		}
		dataFile << endl;
		dataFile << endl;

		dataFile << "# homographies" << endl;
		
		for (unsigned int i = 0; i < homographies.size(); ++i) {
			if (homographies[i] != NULL){
				
				dataFile << "images " << idPairs[i].leftImageID << " " << idPairs[i].rightImageID << endl;
				
				/* homographies are always 3x3 */
				for (int row = 0; row < 3; ++row) {
					for (int col = 0; col < 3; ++col) {
						dataFile << cvmGet(homographies[i], row, col) << " ";
					}
					dataFile << endl;
				}
				dataFile << endl;
			}
		}
		
		
		dataFile << endl;
		
		
		
		dataFile.close();
	}
	
	
}
